# {
#     "personExtKey": "99999992",
#     "cardExtKey": "461794187904352283",
#     "cardMedia": 2,
#     "cardNo": 10000001,
#     "cardFixedNo": 3024265152,
#     "cardState": 60,
#     "stateChangeTime": "2023-05-09 09:04:22",
#     "issueTime": "2023-05-09 08:44:10",
#     "beginTime": "2023-05-09 00:00:00",
#     "endTime": "2024-05-15 14:10:24",
#     "dataSysCode": "0",
#     "remarks": "新增发卡",
#     "isDeleted": false,
#     "deleteTime": null,
#     "modifyTime": "2023-05-10 13:08:30",
#     "sysModifyTime": "2023-05-18 19:05:16"
# }

from module.huada.entity.base_entity import BaseEntity
from plugin import MSsqlClient, Mylogger, MyTime
from module.huada.entity.usercard_entity import  user_cache


class VisitorCardEntity(BaseEntity):
    url = 'tunion/get/exteriorcard'
    table_name = "visitor_card"
    create_table = True
    api_data_list = []
    get_time = "2000-01-01 00:00:00"
    order_by = "modifyTime"
    sync_list = []
    write_back_dict = {}
    update_cache_time = "2000-01-01 00:00:00"

    def __init__(self, **kwargs):
        """
        :param personExtKey: 外部人员主键
        :param cardExtKey: 外部卡片主键
        :param cardMedia: 卡介质
        :param cardNo: 卡号 10进制
        :param cardFixedNo: 固定卡号
        :param cardState: 卡片状态
        :param stateChangeTime: 状态变更时间
        :param issueTime: 发卡时间
        :param beginTime: 有效期开始时间
        :param endTime: 有效期结束时间
        :param dataSysCode: 数据来源
        :param remarks: 备注
        :param isDeleted: 是否删除
        :param deleteTime: 删除时间
        :param modifyTime: 修改时间
        :param sysModifyTime: 系统修改时间
        """
        self.personExtKey = kwargs.get("personExtKey")
        self.cardExtKey = kwargs.get("cardExtKey")
        self.cardMedia = kwargs.get("cardMedia")
        self.cardNo = kwargs.get("cardNo")
        self.cardFixedNo = kwargs.get("cardFixedNo")
        self.cardState = kwargs.get("cardState")
        self.stateChangeTime = kwargs.get("stateChangeTime")
        self.issueTime = kwargs.get("issueTime")
        self.beginTime = kwargs.get("beginTime")
        self.endTime = kwargs.get("endTime")
        self.dataSysCode = kwargs.get("dataSysCode")
        self.remarks = kwargs.get("remarks")
        self.isDeleted = kwargs.get("isDeleted")
        self.deleteTime = kwargs.get("deleteTime")
        self.modifyTime = kwargs.get("modifyTime")
        self.sysModifyTime = kwargs.get("sysModifyTime")
        self.isdeal = kwargs.get("isdeal") or 0
        self.id = kwargs.get("id") or 0

    @classmethod
    def do_sync(cls, client: MSsqlClient, objs: list[BaseEntity]):
        """ 同步数据到数据库 """

        result_num = [0, 0] # 写，删
        for obj in objs:
            # 将10进制的obj.cardFixedNo转成16进制
            cardno = str(hex(int(obj.cardFixedNo)).upper()).removeprefix('0X')

            result = 0
            if obj.isDeleted == "True":
                # 删除
                result = client.execute(f"""
                delete from acscon_usercard where cardid = (select id from acscon_card where cardno = '{cardno}')
                delete from acscon_card where cardno = '{cardno}'
                """)
                if result == 0:
                    Mylogger.error(f'删除失败，没有找到对应凭证 {cardno}')
                result = 1
                result_num[1] += 1
            else:
                if not check_user_exists(obj.personExtKey):
                    # not user_cache.__contains__(obj.personExtKey) or user_cache[obj.personExtKey] == "":
                    Mylogger.info(f"卡 {cardno} 所属外部用户 {obj.personExtKey} 不存在")
                else:
                    card_state = 0
                    if obj.cardState == "20":
                        card_state = 1  # 正常
                    elif obj.cardState == "30":
                        card_state = 4  # 作废
                    elif obj.cardState == "40":
                        card_state = 0  # 挂失
                    else:
                        card_state = 3  # 停用
                    result = client.execute(f"""
                    if not exists(select 1 from acscon_card where cardno = '{cardno}')
                    begin
                        insert into 
                            acscon_card (
                                cardno
                                ,typeid
                                ,status
                                ,startdate
                                ,enddate
                                ,cardpwd
                                ,level
                                ,idtype
                                ,idapplication
                                ,descr)
                            values (
                                '{cardno}'
                                ,(select id from acscon_cardtype where type = 0)
                                ,{card_state}
                                ,'{obj.beginTime}'
                                ,'{obj.endTime}'
                                ,'sxNJjMc+UMo='
                                ,5
                                ,0
                                ,63
                                ,'{obj.remarks}'
                                )

                        insert into acscon_usercard(uid,cardid)
                        values('{user_cache[obj.personExtKey]}',(select id from acscon_card where cardno = '{cardno}'))
                    end
                    else
                    begin
                        update acscon_card set status = {card_state}, startdate = '{obj.beginTime}', enddate = '{obj.endTime}', descr = '{obj.remarks}'
                        where cardno = '{cardno}'
                        update acscon_usercard set uid = '{user_cache[obj.personExtKey]}' where cardid = (select id from acscon_card where cardno = '{cardno}')
                    end
                    """)
                    result_num[0] += 1

            if result is not None:
                # 同步成功，key = 1 ,否则isdeal 减一
                key = 1 if result == 1 else (int(obj.isdeal) - 1)
                if not cls.write_back_dict.__contains__(str(key)):
                    cls.write_back_dict[str(key)] = []

                cls.write_back_dict[str(key)].append(str(obj.id))

        Mylogger.info("visitorcard同步成功，写入：" + str(result_num[0]) + "，删除：" + str(result_num[1]))
        return super().do_sync(client, objs)



def check_user_exists(usercode):
    from config import Config
    client = MSsqlClient(charset='cp936', **Config.module_config.huada.client_link)
    sql = f"select id from acscon_user where usercode = '{usercode}'"
    result = client.select_to_dict(sql)
    if result and len(result) > 0:
        user_cache[usercode] = result[0]['id'] # 加入缓存
        return True
    else:
        return False
